#!/bin/sh
# Copyright (C) 2007 X-Wrt.org
START=01

. /etc/syslog.default
syslogd_bin="/sbin/syslogd"
dmesg_bin="/bin/dmesg"
klogd_bin="/sbin/klogd"

start() {
	[ -n "$(ps | grep [s]yslogd)" -o -n "$(ps | grep [k]logd)" ] && stop

	#log_mark=$(nvram get log_mark)
	#[ "$log_mark" -gt 0 ] 2>>/dev/null || log_mark=$DEFAULT_log_mark
	log_mark="0"
	log_type=$(nvram get log_type)
	[ "$log_type" = "circular" -o "$log_type" = "file" ] 2>/dev/null || log_type=$DEFAULT_log_type
	log_file=$(nvram get log_file)
	[ -z "$log_file" ] && log_file=$DEFAULT_log_file
	log_size=$(nvram get log_size)
	[ "$log_size" -gt 0 ] 2>/dev/null || log_size=$DEFAULT_log_size
	log_ipaddr=$(nvram get log_ipaddr)
	[ "$log_ipaddr" != "" ] && {
		IPCALC_CMD=$(which ipcalc.sh 2>/dev/null)
		[ "$IPCALC_CMD" = "" ] && IPCALC_CMD=$(which ipcalc 2>/dev/null)
		[ "$IPCALC_CMD" != "" ] && {
			eval $($IPCALC_CMD "$log_ipaddr")
			[ "$log_ipaddr" != "$IP" ] && log_ipaddr=""
		}
	}
	log_port=$(nvram get log_port)
	[ "$log_port" -lt 1 -o "$log_port" -gt 65535 ] 2>/dev/null && log_port=$DEFAULT_log_port
	if [ "$log_type" = "circular" ]; then
		SYSLOG_CMD="-C$log_size -m $log_mark ${log_ipaddr:+-L -R $log_ipaddr:$log_port}"
	else
		SYSLOG_CMD="-s $log_size -O $log_file -m $log_mark ${log_ipaddr:+-L -R $log_ipaddr:$log_port}"
	fi
	$syslogd_bin $SYSLOG_CMD

	klog_conloglevel=$(nvram get klog_conloglevel)
	$klogd_bin ${klog_conloglevel:+-c $klog_conloglevel}

	klog_buffersize=$(nvram get klog_buffersize)
	[ -n "$klog_buffersize" ] && $dmesg_bin -s "$klog_buffersize"
}

stop() {
	killall syslogd
	killall klogd
}

case "$1" in
  start) start
	;;
  stop) stop
	;;
  restart) stop
	start
	;;
esac
